package com.javabasic.algorithm.leetcode;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

/**
 * @author mir.xiong
 * @version 1.0
 * @description
 * @see
 * @since Created by work on 2023/12/23 23:19
 */
public class RemoveStonesToMinimizeTheTotal {

    public int minStoneSum(int[] piles, int k) {

        // 排序之后就是一个单调栈
        Arrays.sort(piles);

        // 单调队列--操作之后的数存储队列
        Queue<Integer> opNumQueue = new LinkedList<>();

        int tagIndex = piles.length - 1;
        int temp;
        int pileNum;
        while ((tagIndex >= 0 || !opNumQueue.isEmpty()) && k > 0) {

            if (tagIndex < 0) {
                pileNum = -1;
            } else {
                pileNum = piles[tagIndex];
            }

            if (opNumQueue.isEmpty()) {

                temp = pileNum % 2 == 0 ? pileNum / 2 : pileNum / 2 + 1;
                tagIndex--;
            } else {
                Integer maxOpValue = opNumQueue.peek();
                if (maxOpValue > pileNum) {
                    temp = maxOpValue % 2 == 0 ? maxOpValue / 2 : maxOpValue / 2 + 1;
                    opNumQueue.poll();
                } else {
                    temp = pileNum % 2 == 0 ? pileNum / 2 : pileNum / 2 + 1;
                    tagIndex--;
                }
            }

            opNumQueue.offer(temp);

            k--;
        }

        int sum = 0;
        for (int index = tagIndex; index >= 0; index--) {
            sum += piles[index];
        }

        while (!opNumQueue.isEmpty()) {
            sum += opNumQueue.poll();
        }

        return sum;
    }
}
